/*
 *代码由框架生成,任何更改都可能导致被代码生成器覆盖
 *Repository提供数据库操作，如果要增加数据库操作请在当前目录下Partial文件夹InventoryCountItemRepository编写代码
 */
using VOL.demo.IRepositories;
using VOL.Core.BaseProvider;
using VOL.Core.DbContext;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;

namespace VOL.demo.Repositories
{
    public partial class InventoryCountItemRepository : RepositoryBase<InventoryCountItem>
    , IInventoryCountItemRepository
    {
        public InventoryCountItemRepository(VOLContext dbContext)
        : base(dbContext)
        {

        }
        public static IInventoryCountItemRepository Instance
        {
            get {  return AutofacContainerModule.GetService<IInventoryCountItemRepository>(); }
        }

        /// <summary>
        /// 根据盘点单号获取明细列表
        /// </summary>
        /// <param name="countCode">盘点单号</param>
        /// <returns>明细列表</returns>
        public async Task<List<InventoryCountItem>> GetItemsByCountCodeAsync(string countCode)
        {
            return await DbContext.Queryable<InventoryCountItem>()
                .Where(x => x.CountCode == countCode)
                .ToListAsync();
        }

        /// <summary>
        /// 批量添加盘点明细
        /// </summary>
        /// <param name="items">明细列表</param>
        /// <returns>是否成功</returns>
        public async Task<bool> AddItemsAsync(List<InventoryCountItem> items)
        {
            try
            {
                // 验证必填字段并确保CountStatus符合数据库长度限制
                foreach (var item in items)
                {
                    if (string.IsNullOrEmpty(item.CountCode))
                    {
                        throw new Exception("CountCode不能为空");
                    }
                    if (item.ProductId == 0)
                    {
                        throw new Exception("ProductId不能为空");
                    }
                    
                    // 记录处理前的CountStatus值
                    Console.WriteLine($"处理前 - ProductId: {item.ProductId}, CountStatus: '{item.CountStatus}', 长度: {item.CountStatus?.Length ?? 0}");
                    
                    // 强制限制CountStatus长度为3个字符以内
                    if (!string.IsNullOrEmpty(item.CountStatus))
                    {
                        item.CountStatus = item.CountStatus.Substring(0, Math.Min(3, item.CountStatus.Length));
                    }
                    
                    // 记录处理后的CountStatus值
                    Console.WriteLine($"处理后 - ProductId: {item.ProductId}, CountStatus: '{item.CountStatus}', 长度: {item.CountStatus?.Length ?? 0}");
                }
                
                var result = await DbContext.Insertable(items).ExecuteCommandAsync();
                return result > 0;
            }
            catch (Exception ex)
            {
                // 记录详细异常信息
                Console.WriteLine($"添加盘点明细失败: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                // 如果是SqlSugar异常，尝试获取更详细的信息
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"内部异常: {ex.InnerException.Message}");
                }
                throw; // 重新抛出异常，让上层捕获并返回具体错误信息
            }
        }

        /// <summary>
        /// 根据盘点单号删除明细（物理删除）
        /// </summary>
        /// <param name="countCode">盘点单号</param>
        /// <returns>是否成功</returns>
        public async Task<bool> DeleteItemsByCountCodeAsync(string countCode)
        {
            try
            {
                return await DbContext.Deleteable<InventoryCountItem>()
                    .Where(x => x.CountCode == countCode)
                    .ExecuteCommandAsync() > 0;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 更新明细项
        /// </summary>
        /// <param name="item">明细项</param>
        /// <returns>是否成功</returns>
        public async Task<bool> UpdateItemAsync(InventoryCountItem item)
        {
            try
            {
                return await DbContext.Updateable(item)
                    .Where(x => x.InventoryCountItemId == item.InventoryCountItemId)
                    .ExecuteCommandAsync() > 0;
            }
            catch
            {
                return false;
            }
        }
    }
}
